import _ from 'lodash';
import { history } from 'umi';
import { Modal } from 'antd';
import { getToken } from '@/utils/auth';
import defaultSettings from '@/../config/defaultSettings';

const GlobalModel = {
  namespace: 'global',
  state: {
    checkStatus: REACT_APP_EFFECTIVE_CHECK ? !!getToken() : false,
    safeTime: REACT_APP_EFFECTIVE_TIME, // 用户剩余有效操作时间
    collapsed: false, // 菜单栏的折叠状态
    drawerMenuVisible: false, // 手机视图下侧边菜单栏的显示状态
    screenMode: '', // 屏幕尺寸类型 'xs', 'sm', 'md', 'lg', 'xl', 'xxl'
    isDark: defaultSettings.navTheme === 'realDark', // 是否为深色模式
    primaryColor: defaultSettings.primaryColor, // 主题颜色值
  },
  effects: {
    *safeTimeCountDown(options, { put, select }) {
      const { safeTime, checkStatus } = yield select((state) => state.global);
      if (checkStatus) {
        const nextSeconds = safeTime - 1;
        yield put({ type: 'updateSafeTime', payload: nextSeconds });
        if (nextSeconds <= 0) {
          // 退出
          yield put({ type: 'user/logout' });
          Modal.warning({
            title: '超时',
            content: '鉴于你长时间未操作，当前登录已失效，点击确定返回登录页！',
            keyboard: false,
            okText: '确定',
            onOk() {
              // 前往登录页面
              history.replace({ pathname: '/login' });
            },
          });
        }
      }
    },
  },
  reducers: {
    updateSafeTime(state, action) {
      return {
        ...state,
        safeTime: action.payload,
      };
    },
    closeCheck(state) {
      return {
        ...state,
        checkStatus: false,
      };
    },
    openCheck(state) {
      return {
        ...state,
        checkStatus: true,
        safeTime: REACT_APP_EFFECTIVE_TIME,
      };
    },
    layout(state, action) {
      const layoutOptions = _.pick(action.payload || {}, [
        'collapsed',
        'screenMode',
        'drawerMenuVisible',
      ]);
      return {
        ...state,
        ...layoutOptions,
      };
    },
    updateThemeStatus(state, action) {
      return {
        ...state,
        ...action.payload,
      };
    },
    toggleDrawerMenuVisible(state, action) {
      return {
        ...state,
        drawerMenuVisible: !!action.payload,
      };
    },
  },
  subscriptions: {
    setup({ dispatch, history: subHistory }) {
      return subHistory.listen(({ pathname }) => {
        Modal.destroyAll(); // 浏览器路由切换时关闭弹窗
        dispatch({ type: 'menu/historyChange', payload: pathname });
        if (pathname === '/login') {
          dispatch({ type: 'closeCheck' });
          dispatch({ type: 'user/resetByLogout' });
          dispatch({ type: 'menu/resetByLogout' });
        } else if (!getToken()) {
          history.replace({ pathname: '/login' });
          dispatch({ type: 'closeCheck' });
          dispatch({ type: 'user/resetByLogout' });
          dispatch({ type: 'menu/resetByLogout' });
        }
      });
    },
    intervalCheck({ dispatch }) {
      if (REACT_APP_EFFECTIVE_CHECK) {
        document.addEventListener('mousemove', () => {
          dispatch({
            type: 'updateSafeTime',
            payload: REACT_APP_EFFECTIVE_TIME,
          });
        });
        setInterval(() => {
          try {
            dispatch({ type: 'safeTimeCountDown' });
          } catch (e) {
            console.log('轮询失败');
          }
        }, 60 * 1000);
      }
    },
    screenChange({ dispatch }) {
      const screenListener = () => {
        const width =
          document.body.clientWidth +
          (document.body.scrollHeight > document.body.clientHeight ? 6 : 0);
        const sizeOptions = [576, 768, 992, 1200, 1600];
        const valueOptions = ['xs', 'sm', 'md', 'lg', 'xl', 'xxl'];
        const index = _.findIndex(sizeOptions, (size) => size > width);
        const nextScreenMode =
          index > -1 ? valueOptions[index] || _.last(valueOptions) : _.last(valueOptions);
        const nextCollapsed = _.includes(['md'], nextScreenMode);
        const isMobile = _.includes(['xs', 'sm'], nextScreenMode);
        dispatch({
          type: 'layout',
          payload: {
            screenMode: nextScreenMode,
            collapsed: nextCollapsed,
            drawerMenuVisible: !isMobile,
          },
        });
      };
      screenListener();
      window.addEventListener('resize', screenListener);
    },
  },
};

export default GlobalModel;
